import type { Service } from "../../../api/k8s/types";

import { useK8SApi } from "../../../api/k8s/k8s";
import { SourceMan } from "../providers/sourceCtl";
import type { Ref } from "vue";
import type { ServiceQuery } from "@/views/domain/kubeHud/api/k8s/service";
const { serviceRepo } = useK8SApi();

class ServiceProvider extends SourceMan<Service> {
  get serviceList(): Ref<Service[]> {
    return this.srcList;
  }

  // 获取节点列表
  getServices = async (req?: ServiceQuery) => {
    const res = await serviceRepo.getService({
      ...(req || this.searchQuery.value),
      continue: this.continue,
      limit: this.pager.limit.value
    });
    if (res.ok) {
      this.continue = res.data.metadata.continue;
      this.srcList.value = res.data.items;
      this.pager.total.value =
        res.data.metadata.remainingItemCount ?? res.data.items.length;
    }
  };

  // 获取节点详情
  getServiceDetails = async (query?: ServiceQuery) => {
    const res = await serviceRepo.getServiceDetail(query);
    if (res.ok) {
      this.srcDetail.value = res.data;
      this.srcYamlContent.value = this.objectToYaml(res.data);
      this.yamlDialog.value = true;
    }
  };

  // 更新节点
  updateService = async (data?: ServiceQuery) => {
    const res = await serviceRepo.updateService(data);
    if (res.ok) {
      this.refreshServiceList();
    }
  };

  // delete
  deleteService = async (query?: ServiceQuery) => {
    const res = await serviceRepo.deleteService(query);
    if (res.ok) {
      this.refreshServiceList();
    }
  };

  refreshServiceList = async () => {
    this.continue = undefined;
    await this.getServices();
  };
}

export default new ServiceProvider();
